/**
 * Bestpay.com.cn Inc.
 * Copyright (c) 2011-2019 All Rights Reserved.
 */
package com.study.lickingdogweb.intercept;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study.lickingdogcommon.enums.http.HttpMethodEnums;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 *
 * 拦截器流程
 * preHandle -> Controller -> postHandle -> afterCompletion
 *
 * preHandle: 在请求之前
 * postHandle: 会在DispatcherServlet 进行视图返回渲染之前被调用
 * afterCompletion: 在请求结束后调用
 *
 * @author zhaorongzhang
 * @version Id: LogInterceptor.java, v 0.1 2019/5/16 12:49 zhaorongzhang Exp $$
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {

    /**
     * 日志号
     */
    private final static String THREAD_ID = "THREAD_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 日志号
        String logId;
        // 请求类型（GET,POST）
        String method = request.getMethod();
        // GET 与 POST 获取参数的方式不同
        if (HttpMethodEnums.HTTP_GET.getCode().equals(method)) {
            logId = request.getParameter("logId");
        } else {
            JSONObject parameterMap = JSON.parseObject(new RequestWrapper(request).getBodyString());
            logId = String.valueOf(parameterMap.get("logId"));
        }
        MDC.put(THREAD_ID, logId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除 MDC
        MDC.remove(THREAD_ID);
    }

}